package com.gc.framework.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.gc.common.constant.BusinessConstants;
import com.gc.common.constant.TokenConstant;
import com.gc.common.utils.JwtUtil;
import com.gc.framework.util.FileUploadUtils;
import com.gc.system.domain.SysUser;
import com.gc.system.service.ISysUserService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 接口登录校验--token拦截器
 * @author huruiyan
 * @2020 10.26 上午
 */

@Component
public class LoginInterceptor implements HandlerInterceptor{

    @Autowired
    private ISysUserService userService;
	
  //  在请求处理之前调用,只有返回true才会执行要执行的请求
  @SuppressWarnings("unchecked")
  @Override
  public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

      httpServletResponse.setCharacterEncoding("UTF-8");
      httpServletResponse.setHeader("Access-Control-Allow-Origin","*");
      httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
      httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
      httpServletResponse.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token,Authorization,ybg");
      
      @SuppressWarnings("rawtypes")
      Map ParameterMap =  httpServletRequest.getParameterMap();
      @SuppressWarnings("rawtypes")
      Map reqMap = new HashMap();
      Set<Map.Entry<String,String[]>> entry = ParameterMap.entrySet();
      Iterator<Map.Entry<String,String[]>> it = entry.iterator();
      while (it.hasNext()){
          Map.Entry<String,String[]>  me = it.next();
          String key = me.getKey();
          String value = me.getValue()[0];
          reqMap.put(key,value);
      }
      
      String token = (String) reqMap.get("token");
      
      if (null == token){
          Map<String,Object> map = new HashMap<>();
          map.put("msg","token is null");
          map.put("code","401");
          httpServletResponse.getWriter().write(JSONObject.toJSONString(map));
          return false;
      }else {
    	  Map<String,Object> map = new HashMap<>();
          //boolean result = TokenSign.verify(token);
    	  com.gc.common.json.JSONObject jwtJson = JwtUtil.validateJWT(token);
    	  
    	  boolean result = (boolean) jwtJson.get("Success");
    	  
          if (result){
              //更新存储的token信息
              TokenConstant.updateTokenMap(token);

              //跳过不需要认证校验的接口,直接通过(验证token之后)
              String requestURI = httpServletRequest.getRequestURI();
              String methodName = requestURI.substring(requestURI.lastIndexOf("/")+1);
              if (FileUploadUtils.isAllowedExtension(methodName, BusinessConstants.SKIP_CERTIFICATION_INTERFACE)){
                  return true;
              }

              //判断用户是否审核通过
              Claims parseJWT = JwtUtil.parseJWT(token);
              Long userId = Long.valueOf((String) parseJWT.get("userId"));
              SysUser user = userService.selectUserById(userId);
              if (user == null){
                  map.put("msg","服务器错误,请稍后重试");
                  map.put("code","1010");
                  httpServletResponse.getWriter().write(JSONObject.toJSONString(map));
                  return false;
              }else if (user.getReviewStatus().equals("0")){
                  map.put("msg","您还未认证,请先认证");
                  map.put("code","1006");
                  httpServletResponse.getWriter().write(JSONObject.toJSONString(map));
                  return false;
              }else if (user.getReviewStatus().equals("1")){
                  map.put("msg","您的资料正在审核中,请耐心等待~");
                  map.put("code","1007");
                  httpServletResponse.getWriter().write(JSONObject.toJSONString(map));
                  return false;
              }else if (user.getReviewStatus().equals("3")){
                  map.put("msg","审核未通过,请重新提交认证");
                  map.put("code","1008");
                  httpServletResponse.getWriter().write(JSONObject.toJSONString(map));
                  return false;
              }else if (user.getStatus().equals("1")){
                  map.put("msg","用户已被停用，请联系管理员");
                  map.put("code","1009");
                  httpServletResponse.getWriter().write(JSONObject.toJSONString(map));
                  return false;
              }
              return true;
          }else if(jwtJson.get("ErrCode").equals(1005)) {
        	  map.put("msg","您的登录状态已失效，请重新登录");
              map.put("code","1005");
              httpServletResponse.getWriter().write(JSONObject.toJSONString(map));
              return false;
          }else if(jwtJson.get("ErrCode").equals(1004)) {
        	  map.put("msg","您的登录状态已失效，请重新登录");
              map.put("code","1004");
              httpServletResponse.getWriter().write(JSONObject.toJSONString(map));
              return false;
          }else {
        	  map.put("msg","token is null");
              map.put("code","401");
              httpServletResponse.getWriter().write(JSONObject.toJSONString(map));
              return false;
          }
      }
  }

  //    试图渲染之后执行
  @Override
  public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

  }

  //    在请求处理之后,视图渲染之前执行
  @Override
  public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

  }


}
